package com.wp.targetOffer;

import java.util.ArrayList;

/**
 * Created by 王萍 on 2017/8/12 0012.
 */

/**
 * 输入一个矩阵，按照从外向里以顺时针的顺序依次打印出每一个数字，例如，如果输入如下矩阵：
 * 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
 */
public class 顺时针打印矩阵 {
    public static void main(String[] args) {

        int[][] matrix = {{1, 2}, {3, 4}, {5, 6},{7,8},{9,10}};
        ArrayList<Integer> result = printMatrix(matrix);
        result.stream().forEach(System.out::print);
    }

    /**
     * 按圈数打印
     */
    public static ArrayList<Integer> printMatrix(int[][] matrix) {

        if (matrix.length == 0) return new ArrayList<>();

        int hangshu = matrix.length;//行数
        int lieshu = matrix[0].length;//列数
        ArrayList<Integer> result = new ArrayList<>(hangshu * lieshu);
        int cycleNumber = (Math.min(hangshu, lieshu)-1) / 2 + 1;
        for (int i = 0; i < cycleNumber; i++) {
            for (int k = i; k < lieshu - i; k++) result.add(matrix[i][k]);
            for (int j = i + 1; j < hangshu - i; j++) result.add(matrix[j][lieshu - i- 1] );
            for (int k = lieshu - i - 2; k >= i && hangshu - i -1!= i; k--) result.add(matrix[hangshu - i - 1][k]);
            for (int j = hangshu - i - 2; j > i && lieshu - i -1!=i; j--) result.add(matrix[j][i]);
        }
        return result;
    }
}
